package com.unstoppedable.server;

import java.io.IOException;
import java.util.Map;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;

import net.sf.json.JSONObject;

import org.xml.sax.SAXException;

import com.unstoppedable.common.Configure;
import com.unstoppedable.common.HttpService;
import com.unstoppedable.common.XMLParser;
import com.unstoppedable.protocol.UnifiedOrderReqData;

/**
 * Servlet implementation class Pay
 */
public class Pay extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Pay() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 UnifiedOrderReqData reqData = new UnifiedOrderReqData.UnifiedOrderReqDataBuilder("wx93d4b76a6db7d9b5", "1282629601",
	                "test", new Random().nextInt(100)+"order", 1, "127.0.0.1", "http://www.baidu.com", "JSAPI").setOpenid("oZ3x1jizqDWWScs8r76Ya-9gJyAY").build();
	       try {
			Map<String,Object> map=UnifiedOrder(reqData);
			/*JSONObject jsonObject = JSONObject.fromObject(map);
			request.setAttribute("param", map.toString().replace("=", ":"));*/
			request.setAttribute("test", "y");
			request.setAttribute("map", map);
			request.getRequestDispatcher("/test.jsp").forward(request, response);
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	  public Map<String, Object> UnifiedOrder(UnifiedOrderReqData reqData) throws IOException, SAXException, ParserConfigurationException {
	        String res = HttpService.doPost(Configure.UNIFIED_ORDER_API, reqData);
	       
	        return XMLParser.getMapFromXML(res);
	    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request,response);
	}

}
